package dotdashdot.bradz.trendsettr;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class FragmentItemList extends ListFragment {

	private ClassTrendingContainer trend_container;
	private ClassNetworkHelper helper;
	private ClassFilterPopup info_popup;
	private Activity self;
	private ClassFonts fonts;
	private ClassTrendsettrAdapterAlt adapter;
	private ListView list_view;
	private ArrayList<HashMap<String,String>> aList;
	private ApplicationGlobalVars globals;
	private ClassUserCredentials credentials;
	private ClassUberLogger logger;
	
	Handler myHandler = new Handler() {

  	    @Override
  	    public void handleMessage(Message msg) {
  	        switch (msg.what) {
  	        case 0:
  	        	init_list();
  	        	list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  	              public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
  	              	logger.info("List Item Click Position: " +  position);
  	              	
  	              	//String buffer = ((ApplicationGlobalVars) this.getActivity().getApplication()).get_buffer();
  	              	JSONObject jObject;
					try {
						
						jObject = new JSONObject(aList.get(position).get("Meta").trim());
						if(aList.get(position).containsKey("Picture") && !String.valueOf(aList.get(position).containsKey("Picture")).equals("")){
							logger.info("Valid User Picture!");
							logger.info(String.valueOf(aList.get(position).containsKey("Picture")));
		  	              	jObject.put("picture", aList.get(position).get("Picture"));
						}
	  	              	
	  	              	globals.set_buffer(jObject.toString());
	  	              	mCallbacks.onItemSelected(aList.get(position).get("Trend"));
	  	              	
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
  	              }
  	        	});
	  	        load_filter_popup_task pop_load = new load_filter_popup_task();
	  	        pop_load.list_view = list_view;
	  	        pop_load.execute();
  	            break;
  	        case 6:
  	        	//Sort list by fiilter pop_up then remake the new list
  	        	//init_list();
  	        	filter_things();
  	        	implement_list();
	        	adapter.notifyDataSetChanged();
	        	break;
  	        default:
  	            break;
  	        }
  	    }
  	};
	
	private static final String STATE_ACTIVATED_POSITION = "activated_position";
	private Callbacks mCallbacks = sDummyCallbacks;
	private int mActivatedPosition = ListView.INVALID_POSITION;

	public interface Callbacks {
		public void onItemSelected(String id);
	}

	private static Callbacks sDummyCallbacks = new Callbacks() {
		@Override
		public void onItemSelected(String id) {
		}
	};

	public FragmentItemList() {
	}

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		self = this.getActivity();
		fonts = new ClassFonts(this.getActivity().getAssets());
		trend_container = new ClassTrendingContainer();
		globals = ((ApplicationGlobalVars) self.getApplication());
		credentials = new ClassUserCredentials(globals);
		helper = new ClassNetworkHelper(self,globals);
		adapter = null;
		logger = new ClassUberLogger("FragmentItemList");
		logger.info("OnCreate finished");
	}
	
	public void filter_things(){
		//filters-
		for(String filter : info_popup.get_checked_filters()){
			logger.info("Filter: " + filter);
			if(filter.equalsIgnoreCase("Alphabetical")){
				Collections.sort (aList, new AlphaComparator());
			}
			if(filter.equalsIgnoreCase("Popularity")){
				Collections.sort (aList, new PopularityComparator());			
			}
			if(filter.equalsIgnoreCase("Date Created")){
				Collections.sort (aList, Collections.reverseOrder(new CreatedComparator()));
			}
			if(filter.equalsIgnoreCase("Trend Length")){
				Collections.sort (aList, Collections.reverseOrder(new LengthComparator()));
			}
		}
	}
	
	public class AlphaComparator implements Comparator<HashMap <String, String>> 
  	{
  	    @Override
  	    public int compare (HashMap<String, String> o1, HashMap<String, String> o2) 
  	    {
  	        int c;

  	        c = o1.get ("Trend").compareTo(o2.get ("Trend"));
  	        if (c != 0) return c;

  	        return -1;
  	    }
  	}
	
	public class PopularityComparator implements Comparator<HashMap <String, String>> 
  	{
  	    @Override
  	    public int compare (HashMap<String, String> o1, HashMap<String, String> o2) 
  	    {
  	        /*float votes_a = Float.valueOf(o1.get ("Ups")) / Float.valueOf(o1.get ("Votes"));
  	        float votes_b = Float.valueOf(o2.get ("Ups")) / Float.valueOf(o2.get ("Votes"));*/
  	        
  	        float votes_a = Float.valueOf(o2.get ("Votes"));
	        float votes_b = Float.valueOf(o1.get ("Votes"));
	        
	        float ups_a = Float.valueOf(o2.get ("Ups"));
	        float ups_b = Float.valueOf(o1.get ("Ups"));
	        
	        int return_value = votes_a > votes_b? 1 :
	        	(votes_a < votes_b? -1:
	        		(ups_a > ups_b? 1 :
	        			(ups_a < ups_b? -1:0)));
  	        
  	        return return_value;
  	    }
  	}
	
	public class CreatedComparator implements Comparator<HashMap <String, String>> 
  	{
  	    @Override
  	    public int compare (HashMap<String, String> o1, HashMap<String, String> o2) 
  	    {
  	        DateFormat parser = new SimpleDateFormat("MM.dd.yy");
  	        
  	        Date date1 = null;
  	        Date date2 = null;
			
  	        try {
				date1 = parser.parse(o1.get ("Date Created"));
	  	        date2 = parser.parse(o2.get ("Date Created"));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

  	        int compare_int = date1.compareTo(date2);
  	        //Log.i("Fragment","A: " + o1.get ("Date Created") + " - " + date1.toString());
  	        //Log.i("Fragment","B: " + o2.get ("Date Created") + " - " + date2.toString());
  	        //Log.i("Comparison","Comp: " + compare_int);
  	        
  	        return compare_int;
  	    }
  	}
	
	public class LengthComparator implements Comparator<HashMap <String, String>> 
  	{
  	    @Override
  	    public int compare (HashMap<String, String> o1, HashMap<String, String> o2) 
  	    {
  	    	int votes_a = o1.get ("Trend").length();
  	    	int votes_b = o2.get ("Trend").length();
  	        
  	        return votes_a > votes_b? 1 : -1;
  	    }
  	}
	
	public void init_list(){
		
		((ProgressBar) this.getActivity().findViewById(R.id.progress_see_trend)).setVisibility(View.GONE);
		
		aList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> map;
    	//ArrayList<String> topic_list = new ArrayList<String>();
    	
        logger.info("Creating Trend List");
        
        for(ClassTopic topic:trend_container.get_topic_list()){
        	//topic_list.add(topic.get_name());
        	for(ClassTrend trend:topic.get_trend()){
        		int total = trend.get_info().total;
        		//You can't plot a line with less than two points...
        		if(total>1){
	        		int ups = trend.get_info().ups;
	        		int percent = (int)(((float) ups / (float) total) * 100);
	        		Timestamp created = trend.get_info().date_created;
	        		map = new HashMap<String, String>();
			        map.put("Trend", trend.get_name());
			        map.put("Topic", "" + topic.get_name());
			        map.put("Votes", "" + total);
			        map.put("Ups", "" + percent);     
			        map.put("Date Created", new SimpleDateFormat("MM.dd.yy").format(created));
			        map.put("Picture", "" + trend.get_user_picture());
			        map.put("Voted", "" + trend.get_info().vote);
			        map.put("Meta", "" + trend.get_link());
			        aList.add(map);
			        
			        logger.info("Trend" + trend.get_name());
			        logger.info("Topic" + topic.get_name());
			        logger.info("Votes" + total);
			        logger.info("Ups" + percent);     
			        logger.info("Date Created" + new SimpleDateFormat("MM.dd.yy").format(created));
			        logger.info("Picture" + map.get("Picture"));
			        logger.info("Voted" + trend.get_info().vote);
			        logger.info("Meta" + trend.get_link());
        		}
        	}
        }
        
        implement_list();
	}

	public void implement_list(){
		adapter = new ClassTrendsettrAdapterAlt(self, aList, R.layout.activity_see_trend_row, 
        		new String[]{"Trend","Votes","Ups","Date Created"}, new int[]{R.id.see_trend_trend,R.id.see_trend_votes,
        		R.id.see_trend_ups,R.id.see_trend_date_create}, fonts, info_popup);
        
        list_view.setAdapter(adapter);
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        //This layout contains the list view 
	
        View view = inflater.inflate(R.layout.list, container, false);

        // Initialize the variables:
        list_view = (ListView) view.findViewById(android.R.id.list);
        list_view.setTextFilterEnabled(true);
        list_view.setVerticalFadingEdgeEnabled(true);

		return view;
    }
	
	@Override
	public void onStart(){
		super.onStart();
		if(!credentials.logged_in){
			helper.apply_for_credentials(credentials, myHandler);
		}else{
			format_credentials();
		}
	}
	
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// Restore the previously serialized activated item position.
		if (savedInstanceState != null
				&& savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
			setActivatedPosition(savedInstanceState
					.getInt(STATE_ACTIVATED_POSITION));
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (!(activity instanceof Callbacks)) {
			throw new IllegalStateException(
					"Activity must implement fragment's callbacks.");
		}

		mCallbacks = (Callbacks) activity;
	}

	@Override
	public void onDetach() {
		super.onDetach();

		// Reset the active callbacks interface to the dummy implementation.
		mCallbacks = sDummyCallbacks;
	}

	/*@Override
	public void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id);
	}*/

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if (mActivatedPosition != ListView.INVALID_POSITION) {
			// Serialize and persist the activated item position.
			outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
		}
	}

	private void format_nav_tab(){
		final Button navigation_text = (Button) this.getActivity().findViewById(R.id.top_navigation_button);
		navigation_text.setTypeface(fonts.get_font("cond_medium"));
	}
	
	private void format_credentials(){
		format_nav_tab();
		
    	TextView user_name_text_view = (TextView) this.getActivity().findViewById(R.id.user_name_footer);
    	TextView user_rank_text_view = (TextView) this.getActivity().findViewById(R.id.user_rank_footer);
    	user_name_text_view.setTypeface(fonts.get_font("medium_italic"));
    	user_rank_text_view.setTypeface(fonts.get_font("medium"));
    	user_name_text_view.setText(credentials.name);
    	user_rank_text_view.setText("Trendsettr Rank: "+credentials.rank);
    	
    	globals.set_credentials_store(credentials);
    	
    	if(adapter == null || adapter.getCount()<1 || adapter.isEmpty()){
    		logger.info("There is something wrong with the credentials! Checking if everything's alright on the network.");
    		helper.get_all_from_network_see_trend(trend_container, myHandler);
    	}
    	
    	logger.info("Done formatting credentials");
    }

	public void setActivateOnItemClick(boolean activateOnItemClick) {
		getListView().setChoiceMode(
				activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
						: ListView.CHOICE_MODE_NONE);
	}

	private void setActivatedPosition(int position) {
		if (position == ListView.INVALID_POSITION) {
			getListView().setItemChecked(mActivatedPosition, false);
		} else {
			getListView().setItemChecked(position, true);
		}

		mActivatedPosition = position;
	}
	
	//Make sure that the network is active and working...
  	private class load_filter_popup_task extends AsyncTask<Void, Void, Void> {
  		ArrayList<String> topic_list;
  		ListView list_view;

  		@Override
        protected void onPreExecute() {
  			topic_list = new ArrayList<String>();
  			topic_list.add("Popularity");
  			topic_list.add("Alphabetical");
  			topic_list.add("Date Created");
  			topic_list.add("Trend Length");
  			logger.info("Filter popup init finished");
  		}
  		
  		@Override
  		protected Void doInBackground(Void... arg0) {
  			info_popup = new ClassFilterPopup(self,fonts,topic_list,list_view,self,list_view, myHandler, true);
  			logger.info("Popup Object Made");
  			return null;
  		}
  		
  		@Override
  	    protected void onPostExecute(Void v) {
  			info_popup.attach_popup_window((View)self.findViewById(R.id.top_navigation_button),self.getWindowManager().getDefaultDisplay());
  			logger.info("Popup object attached to activity");
  		}
  		
  	}
}
